/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.google.gautoard.mapreduce;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.tools.mapreduce.Reducer;
import com.google.appengine.tools.mapreduce.ReducerInput;
import com.google.gautoard.model.ReadingHistory;
import com.google.gautoard.model.Sensor;
import com.googlecode.objectify.Key;
import java.util.Date;
import java.util.StringTokenizer;
import java.util.logging.Logger;

/**
 *
 * @author dras
 */
public class TemperatureReadingReducer extends Reducer<String, String, ReadingHistory> {

  private static final Logger log = Logger.getLogger(TemperatureReadingReducer.class.getName());

  @Override
  public void reduce(String key, ReducerInput<String> values) {
    String high = "-9999";
    String low = "9999";
    Float val = 0f;
    while (values.hasNext()) {
      String value = values.next();
      val = Float.parseFloat(value);
      //log.log(Level.WARNING, "vals={0}", val);
      if (val.floatValue() > Float.parseFloat(high)) {
        high = value;
      }
      if (val.floatValue() < Float.parseFloat(low)) {
        low = value;
      }
    }
    StringTokenizer st1 = new StringTokenizer(key, ":");
    String sensorid = st1.nextToken();
    String readingdate = st1.nextToken();
    ReadingHistory rhist = new ReadingHistory();
    rhist.setSensor(Key.create(Sensor.class, sensorid));
    rhist.setHigh(high);
    rhist.setLow(low);
    Date d = new Date();
    d.setTime(Long.parseLong(readingdate));
    rhist.setTimestamp(d);
    emit(rhist);
  }
}
